import type { Plugins, Timeout } from '../index.type';
import { useRef } from 'react';

export const useRetryPlugin: Plugins<any, any[]> = (fetchInstance, options) => {
  const { retryCount, retryInterval } = options;

  const timerRef = useRef<Timeout>();
  const countRef = useRef(0);

  if (!retryCount) {
    if (timerRef.current) {
      clearTimeout(timerRef.current);
    }
    return {};
  }

  return {
    onBefore: () => {
      if (retryCount !== -1 && countRef.current > retryCount) {
        // 重试完成，再次run时从头开始重试
        countRef.current = 0;
      }
      if (timerRef.current) {
        clearTimeout(timerRef.current);
      }
    },
    onSuccess: () => {
      countRef.current = 0;
    },
    onError: () => {
      countRef.current += 1;
      if (retryCount === -1 || (retryCount !== -1 && countRef.current <= retryCount)) {
        const timeout = retryInterval ?? Math.min(1000 * 2 * countRef.current, 30000);
        timerRef.current = setTimeout(() => {
          fetchInstance.refresh();
        }, timeout);
      }
    },
    onCancel: () => {
      countRef.current = 0;
      if (timerRef.current) {
        clearTimeout(timerRef.current);
      }
    },
  };
};